import React, {Component} from 'react';
import {
    convertKey, doubleIfNull,
    getCrmByParam,
    getCrmFields,
    getCrmProductsByParam,
    getCrmRecordFromSql,
    intIfNull,
    isBlank, strIfNull
} from "../util/util";
import {API_URL} from "../constants";
import moment from "moment";
import {SearchOutlined} from "@ant-design/icons";
import * as XLSX from 'xlsx';
import {Table, Card, Input, InputNumber, Button, Modal, Typography, message, Tooltip, Upload} from "antd";

const {Text, Link} = Typography;

const ZOHO = window.ZOHO;

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            user: {},
            loading: false,
            modalVisible: false,
            screenHeight: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
            selectedContractRowKeys: [],
            contactData: [],
            dataSource: [],
            selectedRowKeys: [],
            searchInput: [],
            columns: [
                {
                    "title": "Created Time",
                    "dataIndex": "Created_Time",
                    "key": "Created_Time",
                    "width": 200,
                    "type": "datetime"
                },
                {
                    "title": "Parent Id",
                    "dataIndex": "Parent_Id",
                    "key": "Parent_Id",
                    "width": 200,
                    "type": "lookup"
                },
                {
                    "title": "商品编码",
                    "dataIndex": "Product",
                    "key": "Product",
                    "width": 200,
                    "type": "lookup"
                },
                {
                    "title": "客户货号",
                    "dataIndex": "AccountprtNo",
                    "key": "AccountprtNo",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "内部货号",
                    "dataIndex": "internalcode",
                    "key": "internalcode",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "英文品名",
                    "dataIndex": "Englishname",
                    "key": "Englishname",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "纸箱",
                    "dataIndex": "Carton",
                    "key": "Carton",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "图片",
                    "dataIndex": "Picture",
                    "key": "Picture",
                    "width": 200,
                    "type": "fileupload"
                },
                {
                    "title": "入数",
                    "dataIndex": "Nuofboxesinpg",
                    "key": "Nuofboxesinpg",
                    "width": 200,
                    "type": "integer"
                },
                {
                    "title": "USD光板",
                    "dataIndex": "former_price",
                    "key": "former_price",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "单净重G",
                    "dataIndex": "Netweightofinnebox",
                    "key": "Netweightofinnebox",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "内盒数",
                    "dataIndex": "Nuofboxeinnerbox",
                    "key": "Nuofboxeinnerbox",
                    "width": 200,
                    "type": "integer"
                },
                {
                    "title": "长CM",
                    "dataIndex": "Lengthofouterbox",
                    "key": "Lengthofouterbox",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "每箱数量",
                    "dataIndex": "Quantityperbox",
                    "key": "Quantityperbox",
                    "width": 200,
                    "type": "integer",
                    "description": "每箱数量 = 入数*内盒数",
                    "formula": "[Nuofboxesinpg]*[Nuofboxeinnerbox]"
                },
                {
                    "title": "高CM",
                    "dataIndex": "Heightofouterbox",
                    "key": "Heightofouterbox",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "宽CM",
                    "dataIndex": "Cartonwidth",
                    "key": "Cartonwidth",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "USD最终报价G",
                    "dataIndex": "USDFinaloffer",
                    "key": "USDFinaloffer",
                    "width": 200,
                    "type": "double",
                    "description": "USD最终报价 =(((成本+加工费)*((利润+120)/120)+杀菌费+ (包装费*1200/单净重))/汇率 /1200)* 单净重",
                    "formula": "((([Costfee]+[Processingfee])*(([Profit]+120)/120)+[Sterilizationfee]+ ((((([Smallpackage]+[Bigbag]/[Nuofboxesinpg])+([Carton]/([Nuofboxesinpg]*[Nuofboxeinnerbox])))*1.03)*1200)/[Netweightofinnebox]))/[rate] /1200)* [Netweightofinnebox]"
                },
                {
                    "title": "包装单位",
                    "dataIndex": "Packaginunit",
                    "key": "Packaginunit",
                    "width": 200,
                    "type": "lookup"
                },
                {
                    "title": "毛重KG",
                    "dataIndex": "Grossweight",
                    "key": "Grossweight",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "商品库外销价格G",
                    "dataIndex": "Exportprice",
                    "key": "Exportprice",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "保质期",
                    "dataIndex": "Shelflife",
                    "key": "Shelflife",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "USD 外销公斤价",
                    "dataIndex": "USDKilogrampriceforexport",
                    "key": "USDKilogrampriceforexport",
                    "width": 200,
                    "type": "double",
                    "description": "USD 外销公斤价 = ((成本+加工费)*((利润+120)/120)+杀菌费+ (包装费*1200/单净重))/汇率",
                    "formula": "(([Costfee]+[Processingfee])*(([Profit]+120)/120)+[Sterilizationfee]+ ((((([Smallpackage]+[Bigbag]/[Nuofboxesinpg])+([Carton]/([Nuofboxesinpg]*[Nuofboxeinnerbox])))*1.03)*1200)/[Netweightofinnebox]))/[rate]"
                },
                {
                    "title": "包装包数",
                    "dataIndex": "PackagesNumber",
                    "key": "PackagesNumber",
                    "width": 200,
                    "type": "integer"
                },
                {
                    "title": "成本费",
                    "dataIndex": "Costfee",
                    "key": "Costfee",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "利润",
                    "dataIndex": "Profit",
                    "key": "Profit",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "HS编码",
                    "dataIndex": "HSCode",
                    "key": "HSCode",
                    "width": 200,
                    "type": "lookup"
                },
                {
                    "title": "杀菌费",
                    "dataIndex": "Sterilizationfee",
                    "key": "Sterilizationfee",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "加工费",
                    "dataIndex": "Processingfee",
                    "key": "Processingfee",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "商品备注",
                    "dataIndex": "Remarks",
                    "key": "Remarks",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "小包+",
                    "dataIndex": "Smallpackage",
                    "key": "Smallpackage",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "包装费",
                    "dataIndex": "Packagingfee",
                    "key": "Packagingfee",
                    "width": 200,
                    "type": "double",
                    "description": "包装费=((小包+大包/入数)+纸箱/(入数*内盒数))*1.03 ",
                    "formula": "(([Smallpackage]+[Bigbag]/[Nuofboxesinpg])+([Carton]/([Nuofboxesinpg]*[Nuofboxeinnerbox])))*1.03"
                },
                {
                    "title": "大包+",
                    "dataIndex": "Bigbag",
                    "key": "Bigbag",
                    "width": 200,
                    "type": "double"
                },
                {
                    "title": "单位",
                    "dataIndex": "Unit",
                    "key": "Unit",
                    "width": 200,
                    "type": "lookup"
                },
                {
                    "title": "品牌",
                    "dataIndex": "Brand",
                    "key": "Brand",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "中文规格",
                    "dataIndex": "Chinesespecification",
                    "key": "Chinesespecification",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "中文成份",
                    "dataIndex": "Chineseingredients",
                    "key": "Chineseingredients",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "中文品名",
                    "dataIndex": "Productname",
                    "key": "Productname",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "中文生产要求(材质)",
                    "dataIndex": "Chptrequirements_material",
                    "key": "Chptrequirements_material",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "中文包装描述",
                    "dataIndex": "ChinesePackagedesp",
                    "key": "ChinesePackagedesp",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "英文规格",
                    "dataIndex": "Specification",
                    "key": "Specification",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "体积CBM",
                    "dataIndex": "Volume",
                    "key": "Volume",
                    "width": 200,
                    "type": "formula",
                    "formula": "([Lengthofouterbox]*[Cartonwidth]*[Heightofouterbox])/1000000",
                    "n": "体积CBM"
                },
                {
                    "title": "净重KG",
                    "dataIndex": "Netweight",
                    "key": "Netweight",
                    "width": 200,
                    "type": "double",
                    "description": "净重 =单净重*每箱数量/1200",
                    "formula": "([Netweightofinnebox]*[Nuofboxesinpg]*[Nuofboxeinnerbox])/1200"
                },
                {
                    "title": "单位1 1",
                    "dataIndex": "field",
                    "key": "field",
                    "width": 200,
                    "type": "text"
                },
                {
                    "title": "包装单位1 1",
                    "dataIndex": "field1",
                    "key": "field1",
                    "width": 200,
                    "type": "text"
                }
            ],
            productFields: ['HSCode',  'Businesschannels', 'ChinesePackagedesp', 'Productname', 'Chineseingredients', 'Chptrequirements_material', 'Chinesespecification',  'Commission_Rate', 'Usage_Unit', 'internalcode', 'Manufacturer', 'Nuofboxesinpg', 'Nuofboxeinnerbox', 'Packaginunit',  'Exportprice', 'Unit', 'Netweightofinnebox', 'Header', 'Brand', 'ShippingMark', 'Product_Category', 'Product_Active', 'Product_Code', 'Product_Name', 'Handler',  'Volume', 'Netweight', 'Netweight2', 'Cartonwidth', 'Grossweight', 'Lengthofouterbox', 'Heightofouterbox', 'Archive', 'Unit_Price', 'Account', 'AccountprtNo',            'Englishname', 'Specification',  ],
            initObj: null,
        };
    }

    async componentDidMount() {
        let user = {};
        await ZOHO.CRM.CONFIG.getCurrentUser().then(function (data) {
            user = data.users[0]
        });
        this.setState({
            user: user,
            loading: false,
            initObj: window.data.Quotation_PDetails[0]
        });
    }

    handleSave = () => {
        this.setState({loading: true});
        const {selectedRowKeys, dataSource} = this.state
        const LinkingModule8 = [];
        let selectData = [];
        dataSource.forEach(item => {
            if (selectedRowKeys.includes(item.id)) {
                selectData.push(item)
                LinkingModule8.push({
                    AccountOrderNo: item.AccountOrderNo,
                    Product: {
                        id: item.productid,
                        name: item.Product
                    },
                    AccountprtNo: item.AccountprtNo,
                    internalcode: item.internalcode,
                    Productname: item.Productname,
                    Chinesespecification: item.Chinesespecification,
                    Chptrequirements_material: item.Chptrequirements_material,
                    Chineseingredients: item.Chineseingredients,
                    Make: item.Brand,
                    Englishname: item.Englishname,
                    Specification: item.Specification,
                    Nuofboxesinpg: item.Nuofboxesinpg,
                    Nuofboxeinnerbox: item.Nuofboxeinnerbox,
                    Lengthofouterbox: item.Lengthofouterbox,
                    Heightofouterbox: item.Heightofouterbox,
                    Grossweight: item.Grossweight,
                    NumberofCartons: item.NumberofCartons,
                    Cartonwidth: item.Cartonwidth,
                    Netweight: item.Netweight,
                    Volume: item.Volume,
                    Purchaseunitprice: item.List_Price,
                    PurchaseQty: item.ABQuantity,
                    Packagingquantityperpg: item.Packagingquantityperpg,
                    Category: item.Category,
                    id1: item.id,
                    Unit: item.Unit,
                    Packaginunit:item.Packaginunit
                })
            }
        });

        console.log(JSON.stringify(LinkingModule8))

        try {
            let selectContactData = dataSource[0];
            console.log(selectContactData)
            ZOHO.CRM.UI.Record.populate({
                LinkingModule8: [],
                ContractDate: null,
                ProcurementTerms: null,
                AccountOrderNo: null,
                id1: null,
                field1: null,
                Currency: null,
            }).then((data) => {
                let Subjects = [];
                let id1 = [];
                selectData.forEach(item => {
                    if (!id1.includes(item.Parent_Id.id)) {
                        id1.push(item.Parent_Id.id)
                        Subjects.push(item.Subject)
                    }
                })

                ZOHO.CRM.UI.Record.populate({
                    LinkingModule8: LinkingModule8,
                    ContractDate: selectContactData.ContractDate,
                    ProcurementTerms: selectContactData.Terms_and_Conditions,
                    AccountOrderNo: selectContactData.AccountOrderNo,
                    id1: id1,
                    field1: Subjects.toString().replaceAll(",", "/"),
                    Currency: selectContactData.Currency
                }).then((data) => {
                    ZOHO.CRM.UI.Popup.close().then(() => {
                        this.setState({loading: false});
                    });
                    console.log(data)
                }).finally(() => {
                    this.setState({loading: false});

                })
            })

        } catch (e) {
            console.log(e)
        }

    };

    handleModalClose = () => {
        this.setState({modalVisible: false})
    };

    importFile = (file, fileList) => {
        let reader = new FileReader();
        const {columns, productFields, initObj, integratedObj} = this.state
        console.log(integratedObj)
        this.setState({loading: true})
        reader.onload = async (ev) => {
            try {
                var data = ev.target.result

                var workbook = XLSX.read(data, {
                    type: 'binary'
                }) // 以二进制流方式读取得到整份excel表格对象
                var persons = []; // 存储获取到的数据
            } catch (e) {
                console.log(e);
                console.log('文件类型不正确');
                return;
            }
            // 表格的表格范围，可用于判断表头是否数量是否正确
            var fromTo = '';
            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'];

                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {defval: ""}));
                    break; // 如果只取第一张表，就取消注释这行
                }
            }
            let keyMap = {};
            let typeMap = {};
            columns.forEach(column => {
                keyMap[column.title] = column.dataIndex
                typeMap[column.dataIndex] = {
                    type: column.type,
                    lookupModuleName: column.lookupModuleName,
                    formula: column.formula,
                }
            })

            console.log(keyMap)
            //在控制台打印出来表格中的数据
            let resultData = convertKey(persons, keyMap)
            console.log(resultData);
            try {
                let productBatches = [];
                let products = [];
                resultData.forEach(item => {
                    products.push("'" + item.Product + "'")
                    if (products.length === 50) {
                        productBatches.push(products)
                        products = [];
                    }
                })
                if (products.length > 0) {
                    productBatches.push(products)
                }
                let productMap = {}
                if (productBatches.length > 0) {
                    for (const batch of productBatches) {
                        const result = await getCrmRecordFromSql(`select ${productFields} from Products where Product_Name in (${batch})`);
                        if (!isBlank(result)) {
                            result.forEach(item => {
                                productMap[item.Product_Name] = item;
                            });
                        }
                    }
                }
                const newData = [];
                console.log(typeMap)
                let emptyProduct = [];
                // 先获取基本数据
                resultData.forEach((item, index) => {
                    let product = productMap[item.Product];
                    const newobj = {...initObj};
                    newobj.key = (index + 1);
                    newobj.Name = ((index + 1)) + "";
                    newobj.rate = window.data.Exchange_Rate
                    if (!isBlank(product)) {
                        newobj.Product = {
                            id: product.id,
                            name: product.Product_Name
                        }
                    }

                    Object.keys(newobj).forEach(key => {
                        if (key === "id" || key === "Product" || key === "key") {
                            return;
                        }
                        if (!item.hasOwnProperty(key)) {
                            return;
                        }
                        let value;
                        switch (typeMap[key].type) {
                            case "text":
                                value = strIfNull(item[key])
                                break
                            case "lookup":
                                break
                            case "double":
                                value = doubleIfNull(item[key])
                                break
                            case "integer":
                                value = intIfNull(item[key])
                                break
                        }
                        // 报价以excel中的值为主可以覆盖产品带入的值
                        if (!isBlank(product)) {
                            if (product.hasOwnProperty(key)) {
                                newobj[key] = isBlank(item[key]) ? isBlank(product[key]) ? newobj[key] : product[key] : isBlank(item[key]) ? newobj[key] : value;
                                return;
                            }
                        }
                        newobj[key] = isBlank(item[key]) ? newobj[key] : value;
                    });

                    newData.push(newobj)
                })
                if (emptyProduct.length > 0) {
                    message.error(`以下产品${emptyProduct}不存在`)
                }
                // 二次循环计算公式字段
                newData.forEach(item => {
                    Object.keys(item).forEach(key => {
                        if (isBlank(typeMap[key]?.formula)) {
                            return;
                        }
                        const replacedFormula = typeMap[key].formula.replace(/\[(.*?)\]/g, (match, fieldName) => item[fieldName]);
                        let result = 0;
                        try {
                            let digit = 4;
                            if (typeMap[key].formula.type === "int") {
                                digit = 0;
                            }
                            // 使用 eval() 计算表达式
                            result = eval(replacedFormula);
                            // 检查计算结果是否为有限数值
                            if (!Number.isFinite(result)) {
                                result = 0;
                            }
                            item[key] = Number(result.toFixed(digit))
                        } catch (error) {
                            console.error(`计算公式出错：${error}`);
                        }
                    })
                })
                console.log(newData)
                ZOHO.CRM.UI.Record.populate({
                    Quotation_PDetails: [],
                }).then((data) => {
                    ZOHO.CRM.UI.Record.populate({
                        Quotation_PDetails: newData,
                    }).then((data) => {
                        ZOHO.CRM.UI.Popup.close().then(() => {
                            this.setState({loading: false});
                        });
                        console.log(data)
                    }).finally(() => {
                        this.setState({loading: false});

                    })
                })
            } catch (e) {
                console.log(e)
            } finally {
                this.setState({loading: false})
            }

        }
        reader.readAsBinaryString(file);

    }
    downloadTemplate = () => {
        ZOHO.CRM.API.getOrgVariable('quoteTemplate').then(function (data) {
            // 组装a标签
            let elink = document.createElement("a");
            // 设置下载文件名
            elink.download = `报价明细导入模板.xlsx`;
            elink.style.display = "none";
            elink.href = data.Success.Content;
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            window.URL.revokeObjectURL(elink.href);
        });

    }

    render() {
        const {
            loading,
            modalVisible,
            screenHeight,
            contractColumns,
            contactData,
            selectedContractRowKeys,
            dataSource,
            column,
            selectedRowKeys
        } = this.state;

        return (
            <div>
                <Card className="box-card" style={{width: "355px", margin: "20%"}}>
                    <div style={{width: 300, margin: "10%"}}>
                        <Link onClick={this.downloadTemplate} style={{marginRight: 10}}>
                            下载示例文件
                        </Link><br/>
                        <Upload beforeUpload={this.importFile} accept=".xlsx,.xls" maxCount={1}>
                            <Button type="primary" loading={loading}
                                    style={{marginRight: 10}}>
                                导入文件
                            </Button>
                        </Upload>
                    </div>
                </Card>
            </div>
        );
    }
}

export default App;